package homework;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

public class HashTable {
    private final int HASH_TABLE_SIZE = 17;
    private ArrayList<LinkedList<Student>> array = null;

    public HashTable() {
        array = new ArrayList<LinkedList<Student>>(HASH_TABLE_SIZE);
        for (int i = 0; i <= HASH_TABLE_SIZE; i++) {
            array.add(null);
        }
    }

    private int hash(int id) {
        return id % 17;
    }

    public boolean put(Student student) {
        if (array.get(hash(student.id)) == null) {
            LinkedList<Student> list = new LinkedList<>();
            list.add(student);
            array.set(hash(student.id), list);
        } else {
            array.get(hash(student.id)).add(student);
        }
        return true;
    }

    public Student get(int id) throws Exception {
        LinkedList<Student> list = array.get(hash(id));
        if (list == null) {
            throw new Exception("当前元素不存在");
        } else {
            for (Student student : list) {
                if (student.id == id) {
                    return student;
                }
            }
            throw new Exception("当前元素不存在");
        }
    }
}
